package com.css.zfzx.sjcj.modules.hddcSamplePoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.superRepository.SuperRepository;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.repository.entity.HddcB4SampledatatableEntity;
import com.css.zfzx.sjcj.modules.hddcB4_SampleDataTable.service.HddcB4SampledatatableService;
import com.css.zfzx.sjcj.modules.hddcDrillHole.repository.entity.HddcDrillholeEntity;
import com.css.zfzx.sjcj.modules.hddcDrillHole.service.HddcDrillholeService;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.repository.HddcSamplepointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.repository.HddcSamplepointRepository;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.repository.entity.HddcSamplepointEntity;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.service.HddcSamplepointService;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.viewobjects.HddcSamplepointQueryParams;
import com.css.zfzx.sjcj.modules.hddcSamplePoint.viewobjects.HddcSamplepointVO;
import com.css.zfzx.sjcj.modules.hddcTrench.repository.entity.HddcTrenchEntity;
import com.css.zfzx.sjcj.modules.hddcTrench.service.HddcTrenchService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author zhangcong
 * @date 2020-11-28
 */
@Service
public class HddcSamplepointServiceImpl implements HddcSamplepointService {

    @Autowired
    private HddcSamplepointRepository hddcSamplepointRepository;
    @Autowired
    private HddcSamplepointNativeRepository hddcSamplepointNativeRepository;
    @Autowired
    private HddcB4SampledatatableService hddcB4SampledatatableService;

    @Override
    public JSONObject queryHddcSamplepoints(HddcSamplepointQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcSamplepointEntity> hddcSamplepointPage = this.hddcSamplepointNativeRepository.queryHddcSamplepoints(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcSamplepointPage);
        return jsonObject;
    }


    @Override
    public HddcSamplepointEntity getHddcSamplepoint(String id) {
        HddcSamplepointEntity hddcSamplepoint = this.hddcSamplepointRepository.findById(id).orElse(null);
        return hddcSamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcSamplepointEntity saveHddcSamplepoint(HddcSamplepointEntity hddcSamplepoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcSamplepoint.setUuid(uuid);
        hddcSamplepoint.setQualityinspectionStatus("0");
        hddcSamplepoint.setCreateUser(PlatformSessionUtils.getUserId());
        hddcSamplepoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcSamplepoint.setIsValid("1");
        this.hddcSamplepointRepository.save(hddcSamplepoint);
        return hddcSamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcSamplepointEntity updateHddcSamplepoint(HddcSamplepointEntity hddcSamplepoint) {
        UpdateUtil.copyNullProperties(hddcSamplepointRepository.findByUuidAndIsValid(hddcSamplepoint.getUuid(), "1"),
                hddcSamplepoint);
        hddcSamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcSamplepoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcSamplepointRepository.save(hddcSamplepoint);
        return hddcSamplepoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcSamplepoints(List<String> ids) {
        List<HddcSamplepointEntity> hddcSamplepointList = this.hddcSamplepointRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcSamplepointList) && hddcSamplepointList.size() > 0) {
            for (HddcSamplepointEntity hddcSamplepoint : hddcSamplepointList) {
                hddcSamplepoint.setIsValid("0");
                hddcSamplepoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcSamplepoint.setUpdateTime(new Date());
                this.hddcSamplepointRepository.save(hddcSamplepoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcSamplepointQueryParams queryParams, HttpServletResponse response) {
        List<HddcSamplepointEntity> yhDisasterEntities = hddcSamplepointNativeRepository.exportYhDisasters(queryParams);
        List<HddcSamplepointVO> list = new ArrayList<>();
        for (HddcSamplepointEntity entity : yhDisasterEntities) {
            HddcSamplepointVO yhDisasterVO = new HddcSamplepointVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "采样点-点", "采样点-点", HddcSamplepointVO.class, "采样点-点.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcSamplepointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcSamplepointVO.class, params);
            List<HddcSamplepointVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size()));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcSamplepointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcSamplepointVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    @Autowired
    SuperRepository superRepository;
    @Transactional
    @Override
    public int dataQualityCheck() {
        List<HddcSamplepointEntity> listAll = hddcSamplepointRepository.findByAll();
        List<HddcSamplepointEntity> updateList = new ArrayList<>();
        for (HddcSamplepointEntity b2All : listAll) {
            b2All.getId();//采样点编号
            String fieldid = b2All.getFieldid();//野外编号
            String str="";
            if (StringUtils.isEmpty(b2All.getId())){
                str+="【采样点】采样点编号为空。";
            }else {
                HddcB4SampledatatableEntity hddcB4SampledatatableEntity = hddcB4SampledatatableService.findBySamplepointid(b2All.getId());
                if (hddcB4SampledatatableEntity==null){
                    str+="【采样点】表单中的采样点编号与【样品数据表】表单中的采样点编号不一致。";
                }else {
                    if (StringUtils.isEmpty(b2All.getFieldid())){
                        str+="【采样点】野外编号为空。";
                    }else {
                        if (!b2All.getFieldid().equals(hddcB4SampledatatableEntity.getFieldid())){
                            str+="【采样点】表单中的野外编号与【样品数据表】表单中的野外编号不一致。";
                        }
                    }
                }
            }
            if (StringUtils.isEmpty(str)){
                str="【采样点】与【样品数据表】质检成功。";
                b2All.setQualityinspectionStatus("1");
            }else {
                b2All.setQualityinspectionStatus("2");
            }
            b2All.setQualityinspectionComments(null);
            String[] split = str.split("。");
            for (int i = 0; i < split.length; i++) {
                if (i == 0) {
                    b2All.setExtends1(split[i]);
                    b2All.setExtends2(null);
                    b2All.setExtends3(null);
                } else if (i == 1) {
                    b2All.setExtends2(split[i]);
                    b2All.setExtends3(null);
                } else if (i == 2) {
                    b2All.setExtends3(split[i]);
                }
            }
            updateList.add(b2All);
        }
        superRepository.batchUpdate(updateList);
        return 1;
    }

    @Override
    public HddcSamplepointEntity findbyId(String samplepointid) {
        return hddcSamplepointRepository.findbyId(samplepointid);
    }

    @Override
    public HddcSamplepointEntity findBySamplesourceid(String id) {
        return hddcSamplepointRepository.findBySamplesourceidAndIsValid(id,"1");
    }


    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcSamplepointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcSamplepointEntity yhDisasterEntity = new HddcSamplepointEntity();
            HddcSamplepointVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcSamplepoint(yhDisasterEntity);
        }
    }

}
